//
//  DeviceShareVC.m
//  KEREN
//
//  Created by MW on 2023/3/14.
//

#import "DeviceShareVC.h"
#import <ContactsUI/ContactsUI.h>
#import "DeviceShareUserCell.h"
#import "DeviceshareTypeCell.h"
#import "DeviceShareInPhoneVC.h"
#import "DeviceShareInviteVC.h"
@interface DeviceShareVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *userList;
@property (nonatomic, strong) UIView *tbFooterView;
@property (nonatomic, strong) UIView *tbHeaderView;
@property (nonatomic, strong) NSMutableArray *shareUserArrM;
@end

@implementation DeviceShareVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //TODO 国际化
    [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"用车分享"];
    [self getDeviceinfo];
}

- (void)getDeviceinfo{
    WEAKSELF
    [NetworkingTool POST:Device_info parameters:@{@"ebike_id":@(_deviceInfo.Id)} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            NSDictionary *dict = response[@"data"];
            weakSelf.deviceInfo = [DeviceInfo initWithDictionary:dict];
            weakSelf.tableView.tableHeaderView = weakSelf.tbHeaderView;
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getDevicesharelist];
}

- (void)getDevicesharelist{
    WEAKSELF
    NSDictionary *parameters = @{@"ebike_id":@(_deviceInfo.Id),@"type":@(0)};
    [NetworkingTool POST:Device_share_list parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if(response[@"data"][@"list"] && [response[@"data"][@"list"] isKindOfClass:[NSArray class]]){
                [weakSelf.shareUserArrM removeAllObjects];
                NSArray *arr = response[@"data"][@"list"];
                for (int i = 0; i < arr.count; i ++) {
                    NSDictionary *dict = arr[i];
                    [weakSelf.shareUserArrM addObject:dict];
                }
                if(weakSelf.shareUserArrM.count == 0){
                    weakSelf.tableView.tableFooterView = self.tbFooterView;
                }else{
                    weakSelf.tableView.tableFooterView = nil;
                }
                [weakSelf.tableView reloadData];
            }else{
                weakSelf.tableView.tableFooterView = self.tbFooterView;
                [weakSelf.tableView reloadData];
            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section == 0){
        UIView *headerView = [UIView new];
        headerView.backgroundColor = Main_BackColor;
        return headerView;
    }else{
        UIView *headerView = [UIView new];
        headerView.backgroundColor = Main_BackColor;
        UILabel *tipsLbl = [[UILabel alloc] initWithFrame:CGRectMake(24, 20, DEVICE_WIDTH - 48, 21)];
        //TODO 国际化
        tipsLbl.text = [NSString stringWithFormat:@"分享用户（%lu）",(unsigned long)self.shareUserArrM.count];
        tipsLbl.textColor = Color_86898E;
        tipsLbl.font = Font(14);
        [headerView addSubview:tipsLbl];
        return headerView;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [UIView new];
    return footerView;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0){
        return 0;
    }else{
        return 50;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return 2;
    }else{
        return self.shareUserArrM.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        DeviceshareTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DeviceshareTypeCell"];
        if(indexPath.row == 0){
            cell.icon.image = [UIImage imageNamed:@"share_type_iphone"];
            cell.title.text = @"搜索手机号进行分享";
            cell.dec.text = @"通过输入对方的注册账号的手机号进行分享";
        }else{
            cell.icon.image = [UIImage imageNamed:@"share_type_list"];
            cell.title.text = @"获取手机通讯录进行分享";
            cell.dec.text = @"通过获取通讯录选择指定通讯录中的人进行分享";
        }
        return cell;
    }else{
        DeviceShareUserCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DeviceShareUserCell"];
        NSDictionary *dict = self.shareUserArrM[indexPath.row];
        cell.name.text = dict[@"user_name"];
        if([dict[@"share_time"] intValue] > 10 && [dict[@"status"] intValue] != 1){
            cell.phone.text = [NSString stringWithFormat:@"%@   到期时间：%@",dict[@"phone"],[[DeteManager shareInstance] timeFormatted:([dict[@"accepted_at"] intValue]+[dict[@"share_time"] intValue])]];
        }else{
            cell.phone.text = dict[@"phone"];
        }
        if([dict[@"status"] intValue] == 1){
            [cell.Cbtn setTitle:@"等待确认" forState:UIControlStateNormal];
            [cell.Cbtn setTitleColor:Color_107DFF forState:UIControlStateNormal];
        }else if ([dict[@"status"] intValue] == 2){
            [cell.Cbtn setTitle:@"移除" forState:UIControlStateNormal];
            [cell.Cbtn setTitleColor:Color_EA3435 forState:UIControlStateNormal];
            cell.Cbtn.tag = indexPath.row;
            [cell.Cbtn addTarget:self action:@selector(cbtnClick:) forControlEvents:UIControlEventTouchUpInside];
            ///v1/app/share_device/user_share
        }
        
        return cell;
    }
}

- (void)cbtnClick:(UIButton *)btn{
    btn.enabled = NO;
    NSDictionary *dict = self.shareUserArrM[btn.tag];
    if([dict[@"status"] intValue] != 2){
        return;
    }
    WEAKSELF
    NSDictionary *parameters = @{@"id":dict[@"id"]};
    [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
    [NetworkingTool POST:Device_share_delete parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        btn.enabled = YES;
        if([response[@"code"] intValue] == 0){
            [weakSelf.shareUserArrM removeObject:dict];
            [weakSelf.tableView reloadData];
        }else{
            //[[KRAlartManager shareInstance] showErrorAlert:response[@"msg"]];
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if(indexPath.section == 0){
        if(indexPath.row == 0){
            DeviceShareInPhoneVC *vc = [[DeviceShareInPhoneVC alloc] init];
            vc.deviceInfo = self.deviceInfo;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [[KRPhoneContactManager shareInstance] presentAddressBookReadFinishWithPhoneNumber:^(NSString * _Nonnull contactNumber) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSString *phoneNumber = @"";
                    if ([contactNumber hasPrefix:@"+86"]) {
                        phoneNumber = [contactNumber stringByReplacingOccurrencesOfString:@"+86" withString:@""];
                    } else {
                        phoneNumber = contactNumber;
                    }
                    phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:@"（" withString:@""];
                    phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:@"）" withString:@""];
                    phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
                    phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
                    DeviceShareInviteVC *vc = [[DeviceShareInviteVC alloc] init];
                    vc.deviceInfo = self.deviceInfo;
                    vc.photoStr = phoneNumber;
                    [self.navigationController pushViewController:vc animated:YES];
                });
            }];
        }
    }
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVTOP_Height, DEVICE_WIDTH, DEVICE_HEIGHT - NAVTOP_Height)];
        _tableView.backgroundColor = Main_BackColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 80;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        if (@available(iOS 15.0, *)) {
            
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"DeviceshareTypeCell" bundle:nil] forCellReuseIdentifier:@"DeviceshareTypeCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"DeviceShareUserCell" bundle:nil] forCellReuseIdentifier:@"DeviceShareUserCell"];

        [self.view addSubview:_tableView];
    }
    return _tableView;

}

- (UIView *)tbFooterView{
    if(!_tbFooterView){
        _tbFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 320)];
        self.tableView.tableFooterView = _tbFooterView;
        UIImageView *iconImage = [[UIImageView alloc] init];
        [_tbFooterView addSubview:iconImage];
        [iconImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(64);
            make.width.height.offset(176);
            make.centerX.equalTo(self.view);
        }];
        iconImage.image = [UIImage imageNamed:@"share_nouser"];
        UILabel *titleLbl = [[UILabel alloc] init];
        [_tbFooterView addSubview:titleLbl];
        [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(iconImage.mas_bottom).offset(0);
        }];
        titleLbl.font = Font(16);
        titleLbl.textColor = Color_333333;
        titleLbl.text = @"车辆未分享给其他人";
    }
    return _tbFooterView;
}

- (UIView *)tbHeaderView{
    if(!_tbHeaderView){
        _tbHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 228)];
        _tbHeaderView.backgroundColor = Whire_Color;
        UIImageView *backImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"preView"]];
        [_tbHeaderView addSubview:backImageView];
        [backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.right.offset(0);
            make.bottom.offset(-37);
            make.width.offset(193);
        }];
        UIImageView *deviceImageView = [[UIImageView alloc] init];
        [deviceImageView sd_setImageWithURL:[NSURL URLWithString:_deviceInfo.photo] placeholderImage:[UIImage imageNamed:@"devcie_defalaut_icon"] options:SDWebImageRefreshCached];
        [_tbHeaderView addSubview:deviceImageView];
        [deviceImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(0);
            make.top.offset(16);
            make.width.height.offset(193);
        }];
        //ble_icon
        UILabel *typeLbl = [UILabel setLblText:@"蓝牙版" font:BFont(14) withColor:Color_7ACC00 inSubView:_tbHeaderView];
        if(_deviceInfo.socket_type == 0){
            typeLbl.text = @"蓝牙版";
        }else{
            typeLbl.text = @"4G版";
        }
        [typeLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(50);
            make.top.offset(42);
            make.height.offset(20);
        }];
        UIImageView *typeImageView = [[UIImageView alloc] init];
        if(_deviceInfo.socket_type == 0){
            typeImageView.image = [UIImage imageNamed:@"ble_back_icon"];
        }else{
            typeImageView.image = [UIImage imageNamed:@"4G_back_icon"];
        }
        [_tbHeaderView addSubview:typeImageView];
        [typeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(20);
            make.left.offset(25);
            make.centerY.equalTo(typeLbl);
        }];
        
        UILabel *nameLbl = [UILabel setLblText:_deviceInfo.name font:Font(24) withColor:Black_Color inSubView:_tbHeaderView];
        [nameLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(25);
            make.top.equalTo(typeLbl.mas_bottom).offset(2);
            make.height.offset(34);
            make.right.offset(-200);

        }];
        for (int i = 0; i < 5; i ++) {
            UILabel *label = [[UILabel alloc] init];
            [_tbHeaderView addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.offset(25);
                make.top.equalTo(nameLbl.mas_bottom).offset(8 + 20 * i);
                make.right.offset(-180);
            }];
            NSString *str;
            NSArray *attArr = @[];
            if(i == 0){
                attArr = @[@"车    型"];
                str = [NSString stringWithFormat:@"车    型  %@",_deviceInfo.type_name];
            }
            else if(i == 1){
                attArr = @[@"颜    色"];
                str = [NSString stringWithFormat:@"颜    色  %@",_deviceInfo.color];
            }else if (i == 2){
                attArr = @[@"S      N"];
                str = [NSString stringWithFormat:@"S      N  %@",_deviceInfo.sn_code];
            }else if (i == 3){
                attArr = @[@"车架号"];
                str = [NSString stringWithFormat:@"车架号  %@",_deviceInfo.frame_code];
            }else{
                attArr = @[@"电机号"];
                str = [NSString stringWithFormat:@"电机号  %@",_deviceInfo.engine_code];
            }
            NSAttributedString *showAttString = [NSAttributedString getAttributeWith:attArr string:str Font:Font_Medium(12) Color:Black_Color attributeFont:Font_Medium(12) attributeColor:Color_86898E];
            label.attributedText = showAttString;
            [UIView setLineViewWithframe:CGRectMake(0, 227, DEVICE_WIDTH, 1) forinView:_tbHeaderView];
        }
    }
    return _tbHeaderView;
}

- (NSMutableArray *)shareUserArrM{
    if(!_shareUserArrM){
        _shareUserArrM = [NSMutableArray array];
    }
    return _shareUserArrM;
}

@end
